package com.detrum.costomview;

import android.content.Context;
import android.graphics.Canvas;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;


/**
 * Created by lsy on 2018/4/16.
 */

/**
 * 自定义可绘制的View及相关动作的实现
 * Painting(Canvas canvas)中实现基础绘制原始图像
 * Logic()定义相关动画或其他逻辑功能
 */
public abstract class BaseView extends View {
    private MyThread thread;
    private boolean stop;

    public BaseView(Context context) {
        super(context);
    }

    public BaseView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    protected abstract void Logic();

    protected abstract void Painting(Canvas canvas);

    public void stop(){
        stop = true;
        thread = null;
    }

    public void start(int interval){
        stop = false;
        if(thread == null){
            thread = new MyThread(interval);
            thread.start();
        }
    }

    class MyThread extends Thread{
        private int interval;

        public MyThread(int interval) {
            this.interval = interval;
        }

        @Override
        public void run() {
            while (!stop){
                Logic();
                postInvalidate();
                try {
                    Thread.sleep(interval);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected final void onDraw(Canvas canvas) {
        super.onDraw(canvas);
            Painting(canvas);
    }
}
